﻿using IBLL;
using IDAL;
using Model;
using Model.DTO;
using System.ComponentModel.DataAnnotations;

namespace BLL
{
    public class HouseNumBLL : HouseNumIBLL
    {
        public HouseNumBLL(IBaseDAL<HouseNum> Db, IBaseDAL<HouseType> Db2)
        {
            this.Db = Db;
            this.Db2 = Db2;
        }

        public IBaseDAL<HouseNum> Db { get; }
        public IBaseDAL<HouseType> Db2 { get; }

        public async Task<int> AddHouseNum(HouseNum h)
        {
            bool d = Db.GetAll().Any(x => x.HouseNumName == h.HouseNumName);
            if (!d)
            {
                return await Db.AddAsync(h);
            }
            else
            {
                return -1;
            }
           
        }

        public async Task<int> AddRange(List<HouseNum> h)
        {
            return await Db.AddAsyncList(h);
        }

        public HouseNum Fan(int id)
        {
            return  Db.GetAll().FirstOrDefault(x => x.HouseNumId == id);
        }

        public IQueryable<HouseNum> GetHouseNums()
        {
            return Db.GetAll();
        }

        public IQueryable<HouseDTO> Show(string? name, DateTime? d1, DateTime? d2)
        {
            var e = Db.GetAll();
            var q = Db2.GetAll();
            if (!string.IsNullOrEmpty(name))
            { 
                e = e.Where(x => x.HouseNumName.Contains(name));
            }
            if (d1!=null)
            { 
                e = e.Where(x => x.CreateTime >= d1);
            }
            if (d2!=null)
            { 
                var d3 = d2.Value.AddDays(1);
                e = e.Where(x => x.CreateTime < d3);
            }
            var linq = from a in e
                       join b in q
                       on a.HouseTypeId equals b.HouseTypeId
                       select new HouseDTO
                       {
                           HouseNumId = a.HouseNumId,
                           HouseNumName = a.HouseNumName,
                           States = a.States,
                           CreateTime = a.CreateTime,
                           HouseTypeId = a.HouseTypeId,
                           HouseTypeName = b.HouseTypeName,
                           HouseState=a.HouseState
                       };
            return linq;
        }

        public async Task<int> Update(HouseNum h)
        {
            bool d = Db.GetAll().Any(x => x.HouseNumName == h.HouseNumName && x.HouseNumId != h.HouseNumId);
            if (!d)
            {
                return await Db.UpdateAsync(h);
            }
            else
            {
                return -1;
            }
            
        }

        public Task<int> UpdateState(int id)
        {
            var h = Db.GetAll().FirstOrDefault(x => x.HouseNumId == id );
            h.States = false;
            return Db.UpdateAsync(h);
        }
    }
}
